# -*- coding: utf-8 -*-
# @Time    : 2024/10/29 15:47
# @Author  : CHNJX
# @File    : routes.py
# @Desc    : 路由

import json

from flask import Blueprint, request, jsonify
from app.utils.database import db

from ..model import Device, Strategy
from ..services.job_service import JobService
from ..core.scheduler import SchedulerService
from ..core.excel_api import get_excel_data

bp = Blueprint('api', __name__)

job_service = JobService()
scheduler_service = SchedulerService()


@bp.route('/schedule_job', methods=['POST'])
def schedule_job():
    """创建任务监控"""
    data = json.loads(get_excel_data())

    device_run_msg = []
    for device_name, device_params in data.items():
        # 收集设备的所有策略
        strategies = []
        job_ids = []

        for param in device_params:
            trigger_time = param.get('trigger_time')
            if not trigger_time:
                return jsonify({"status": "error", "message": "没有触发时间"}), 400

            # 为每个策略生成ID
            job_id = scheduler_service.schedule_job(trigger_time, device_name, param)
            job_ids.append(job_id)

            # 保存策略信息
            strategies.append(param)

        # 启动设备的监控
        scheduler_service.pipeline_monitor.start_monitor(device_name, strategies)

        device_run_msg.append({
            "device_name": device_name,
            "ids": job_ids,
        })

    return jsonify({
        "status": "success",
        "message": "Job scheduled successfully",
        "job_msg": device_run_msg
    }), 200


@bp.route('/devices', methods=['GET'])
def get_devices():
    devices = Device.query.all()
    return jsonify({
        "status": "success",
        "data": [{"id": d.id, "name": d.name} for d in devices]
    })


@bp.route('/strategies', methods=['GET'])
def get_strategies_data():
    s_data = Strategy.query.all()
    res = []
    for s in s_data:
        s_dict = {}
        device_name = getattr(Device.query.filter_by(id=s.device_id).first(), 'name', None)
        s_dict['device_name'] = device_name
        s_dict['strategy_desc'] = s.description
        s_dict['weekdays'] = s.weekdays
        s_dict['test_case'] = s.test_case
        s_dict['id'] = s.id
        res.append(s_dict)
    return jsonify({
        "status": "success",
        "data": res
    })


@bp.route('/strategies', methods=['POST'])
def add_strategies_data():
    # 更新策略
    data = request.get_json()

    device_id = data.get('device_id')
    strategies_data = data.get('strategies')

    # 查找设备
    device = Device.query.get(device_id)
    if not device:
        return jsonify({"error": "Device not found"}), 404

    # 清空旧策略
    Strategy.query.filter_by(device_id=device.id).delete()

    # 遍历每个新的策略数据并保存到数据库
    for strategy_data in strategies_data:
        strategy = Strategy(
            device_id=device.id,
            weekdays=','.join(strategy_data['weekdays']),  # 将星期数组转换为字符串
            test_case=strategy_data['test_case'],
            description=strategy_data.get('strategy_desc', None),  # 获取描述
        )
        db.session.add(strategy)

    db.session.commit()  # 提交事务

    return jsonify({"message": "Strategies updated successfully"}), 201


@bp.route('/get_strategies', methods=['GET'])
def get_strategies():
    """获取策略列表"""
    try:
        data = json.loads(get_excel_data())
        # 转换数据格式以匹配前端表格结构
        strategies_list = []
        for device_name, device_params in data.items():
            for param in device_params:
                strategy = {
                    "设备名称": device_name,
                    "策略编号": f"策略{len(strategies_list) + 1}",
                    "运行时间": param['trigger_time'],
                    "执行用例": param['TESTSUITE_NAME'],
                    "运行次数": 5  # 可以根据实际需求修改
                }
                strategies_list.append(strategy)

        return jsonify({
            "status": "success",
            "data": strategies_list
        }), 200
    except Exception as e:
        return jsonify({
            "status": "error",
            "message": str(e)
        }), 500


@bp.route('/manual_trigger', methods=['POST'])
def manual_trigger():
    """手动触发任务"""
    data = request.get_json()
    device_name = data.get('DEVICE_NAME')

    job_service.execute_job(data, device_name)
    return jsonify({
        "status": "success",
        "message": "Job scheduled successfully",
    }), 200


@bp.route('/cancel_schedule', methods=['POST'])
def cancel_schedule():
    """取消调度任务"""
    data = request.get_json()
    device_name = data.get('DEVICE_NAME')

    if not device_name:
        return jsonify({"status": "error", "message": "DEVICE_NAME is required"}), 400

    result = job_service.cancel_device_jobs(device_name)
    status_code = 200 if result["status"] == "success" else 404
    return jsonify(result), status_code


@bp.route('/cancel_all', methods=['GET'])
def cancel_all():
    """取消所有任务"""
    result = job_service.cancel_all_jobs()
    status_code = 200 if result["status"] == "success" else 404
    return jsonify(result), status_code


@bp.route('/monitor/status', methods=['GET'])
def get_monitor_status():
    """获取所有设备的监控状态"""
    status = scheduler_service.pipeline_monitor.get_status()
    return jsonify({
        "status": "success",
        "data": "停止成功"
    })
